package com.yu.core.controller;


import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.alibaba.fastjson.JSONArray;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.plugin.activerecord.Page;
import com.yu.core.controller.user.UserValidator;
import com.yu.interceptor.LoginInterceptor;
import com.yu.model.Admin;
import com.yu.model.Article;
import com.yu.model.Config;
import com.yu.model.Course;
import com.yu.model.Focus;
import com.yu.model.House;
import com.yu.model.Member;
import com.yu.model.MemberDetail;
import com.yu.model.MemberGroup;
import com.yu.model.Module;
import com.yu.model.Order;
import com.yu.model.User;
import com.yu.util.CookiesUtil;
import com.yu.util.DateUtil;
import com.yu.util.HttpUtils;
import com.yu.util.JPushClientDemo;
import com.yu.util.StringUtil;
import com.yu.util.UuidUtil;
import com.yu.util.WeiXinUtil;

public class AdminController extends Controller {
	
	/*
	 * 退出登录
	 */
	@Before(LoginInterceptor.class)
	public void signOut(){
		getSession().removeAttribute("admin");
		render("login.html");
	}
	
	public void index(){
		if (getSession().getAttribute("admin") !=null){
			forwardAction("/admin/orderList");
		} else {
			render("login.html");
		}
		
	}
	
	public void login(){
		//0 普通用户 1 服务人员 2 房东   101 后台操作人员 1001 超级管理员
		if (getSession().getAttribute("admin") !=null){
			User user = (User) getSession().getAttribute("admin");
			setAttr("admin", user);
			setAttr("type", user.getInt("type"));
			forwardAction("/admin/orderList");
		} else {
			String username = getPara("username") == null?"":getPara("username").trim();
			String password = getPara("password") == null?"":getPara("password").trim();
			User admin = User.dao.findFirst("select * from w_user where account ='"+username+"' and password = '"+password+"' and valid > -1 order by id desc limit 1");
			if (admin == null){
				setAttr("message", "账号或密码错误！");
				render("login.html");
			} else {
				int type = admin.getInt("type");
				if(type == 101 || type == 1001){
					getSession().setAttribute("admin", admin);
					getSession().setAttribute("type", admin.getInt("type"));
					setAttr("admin", admin);
					setAttr("type", admin.getInt("type"));
					forwardAction("/admin/orderList");
				} else {
					setAttr("message", "账号没有权限");
					render("login.html");
				}
				 
			}
		}
	}
	
	
	public final static String case_statusname = " CASE o.`status` WHEN  '-1' THEN '未支付' WHEN  0 THEN '已支付' WHEN  1 THEN  '已接单' WHEN  2 THEN  '已入住' WHEN  3 THEN '打扫中' WHEN  4 THEN '已完成'  WHEN  8  THEN '已评价'  END AS statusname";
	@Before(LoginInterceptor.class)
	public void orderList(){
		int type = 0;
		try {
			type = getParaToInt("type");
		} catch (Exception e) {
		}
		int page = 1;
		if (!StringUtil.isEmpty(getPara("page"))){
			page = getParaToInt("page");
		}
		String andSql = ""; 
		if (!StringUtil.isEmpty(getPara("orderid"))){
			andSql = " and o.orderid = '" + getPara("orderid")+"' ";
		}
		Page<Order> orderList = Order.dao.paginate(page, 20, "SELECT o.id,o.orderid as orderid,FROM_UNIXTIME(o.createtime/ 1000,'%m-%d %H:%i') AS createtime1,FROM_UNIXTIME(o.checkintime/ 1000,'%m-%d %H:%i') AS checkintime1,FROM_UNIXTIME(o.checkouttime/ 1000,'%m-%d %H:%i') AS checkouttime1,FROM_UNIXTIME(o.endtime/1000,'%m-%d %H:%i') AS endtime1,"+case_statusname+",o.price ,h.id as hid,h.name as hname,h.address as haddress ,o.uid as uid ,u.`name` as uname ,u.mobile as umobile ,o.sid as sid ,s.account as account ,o.livescore, o.mannersscore, o.pdetail,o.bpic,o.apic,o.note,o.comment ","FROM w_order AS o LEFT JOIN w_house as h  on o.hid = h.id LEFT JOIN w_user as u  on  o.uid = u.id LEFT JOIN w_user as s  on  o.sid = s.id  WHERE o.valid > - 1  and o.status != -1  and o.type = 0 "+ andSql);
		
		List<User> userList = User.dao.find("select * from w_user where type = 1  order by id desc ");
		setAttr("page", orderList);
		setAttr("orderid", getPara("orderid"));
		setAttr("suserList", userList);
		render("orderList.html");
	}
	
	@Before(LoginInterceptor.class)
	public void order(){
		Order order = Order.dao.findById(getPara("id"));
		setAttr("order", order);
		setAttr("checkintime", DateUtil.getStringDateForH5(order.getLong("checkintime")));
		setAttr("checkouttime", DateUtil.getStringDateForH5(order.getLong("checkouttime")));
		setAttr("endtime", DateUtil.getStringDateForH5(order.getLong("endtime")));
		if (order.get("pdetail") != null){
			JSONArray json = JSONArray.parseArray(order.getStr("pdetail"));
			String result = "";
			for(int i = 0;i < json.size(); i++){
				result += json.getJSONObject(i).get("name") +":"+json.getJSONObject(i).get("price")+ "\n";
			}
			setAttr("result",result);
		}
		render("order.html");
	}
	
	@Before(LoginInterceptor.class)
	public void orderSave(){
		Order order = Order.dao.findById(getPara("id"));
		// 租客信息
		order.set("rentername", getPara("rentername"));
		order.set("rentermobile", getPara("rentermobile"));
		// 入驻时间
		// 2017-09-14T12:12
		String checkintime = getPara("checkintime").replace("T", " ");
		String checkouttime = getPara("checkouttime").replace("T", " ");
		String endtime = getPara("endtime").replace("T", " ");
		try {
			order.set("checkintime", new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(checkintime).getTime());
			order.set("checkouttime", new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(checkouttime).getTime());
			order.set("endtime", new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(endtime).getTime());
		} catch (ParseException e) {
			System.out.println("checkintime:"+getPara("checkintime"));
			System.out.println("checkouttime:"+getPara("checkouttime"));
			System.out.println("endtime:"+getPara("endtime"));
			order.set("checkintime", System.currentTimeMillis());
			order.set("checkouttime", System.currentTimeMillis());
			order.set("endtime", System.currentTimeMillis());
		}
		
		order.set("comment", getPara("comment"));
		order.set("note", getPara("note"));
		order.update();
		renderText("操作成功!");
	}
	
	@Before(LoginInterceptor.class)
	public void userList(){
		int type = 1;
		try {
			type = getParaToInt("type");
		} catch (Exception e) {
		}
		int page = 1;
		if (!StringUtil.isEmpty(getPara("page"))){
			page = getParaToInt("page");
		}
		String andSql = "";
		String account = getPara("account");
		if (!StringUtil.isEmpty(account)){ 
			andSql = " and u.account like '%" + account +"%'";
		}
		
		String q = getPara("q");
		if (!StringUtil.isEmpty(q)){ 
			andSql = " and (u.name like '%" + q +"%'  or u.mobile = '"+ q +"')";
		}
		String sqlSelect = "select u.*,CASE u.status  WHEN  '0' THEN '接单中' else '繁忙中' END AS statusname";
		Page<User> useres = User.dao.paginate(page, 20, sqlSelect, " from w_user as u  where u.valid >-1 and u.type =" +type + andSql +" order by u.id desc" );
		setAttr("page", useres);
		setAttr("account", account);
		setAttr("q", q);
		render("userList"+type+".html");
	}
	
	
	@Before(LoginInterceptor.class)
	public void houseList(){
		int page = 1;
		if (!StringUtil.isEmpty(getPara("page"))){
			page = getParaToInt("page");
		}
		String andSql = "";
		String key = getPara("key");
		if (!StringUtil.isEmpty(key)){ 
			andSql = " and (ownername like '%" + key +"%' or ownermobile = '"+key+"')";
		}
		if (!StringUtil.isEmpty(getPara("status"))){
			andSql += " and  status = "+getPara("status"); 
		}
		String sqlSelect = "select h.*, CASE h.status  WHEN  '0' THEN '未审核' else '审核过' END AS statusname  ";
		Page<House> houses = House.dao.paginate(page, 20, sqlSelect, " from w_house as h where h.valid > -1 " + andSql +" order by h.updatetime asc" );
		setAttr("page", houses);
		setAttr("key", key);
		setAttr("status", getPara("status"));
		render("houseList.html");
	}
	
	@Before(LoginInterceptor.class)
	public void house(){
		House house = House.dao.findById(getPara("id"));
		if (house == null){
			house = new House();
			setAttr("action", "添加");
			house.set("id", 0);
		} else{
			setAttr("action", "修改");
		}
		List<Focus> focusList = Focus.dao.find("select * from w_focus order by id desc ");
		setAttr("focusList", focusList);
		List<User> userList = User.dao.find("select * from w_user where type =2 order by id desc ");
		setAttr("userList", userList);
		setAttr("house",house);
		render("house.html");
	}
	
	@Before(LoginInterceptor.class)
	public void houseSave(){
		House house = House.dao.findById(getPara("id"));
		boolean editflg = true;
		if (house != null) {
		} else {
			house = new House();
			house.set("createtime", System.currentTimeMillis());
			house.set("valid", 0);
			editflg = false;
		}
		house.set("name",getPara("name"));
		// 布草
		house.set("linen",getPara("linen"));
		// 1.5 床单
		house.set("five",getPara("five"));
		house.set("eight",getPara("eight"));
		
		house.set("lon",getPara("lon"));
		house.set("lat",getPara("lat"));
		if (!StringUtil.isEmpty(getPara("province")))
			house.set("province", getPara("province"));
		if (!StringUtil.isEmpty(getPara("city")))
			house.set("city", getPara("city"));
		if (!StringUtil.isEmpty(getPara("village")))
			house.set("village", getPara("village"));
		if (!StringUtil.isEmpty(getPara("road")))
			house.set("road", getPara("road"));
		house.set("address", getPara("address"));
		house.set("status",getPara("status"));
		house.set("fid",getPara("fid"));
		house.set("ownername",getPara("ownername"));
		house.set("ownermobile",getPara("ownermobile"));
		house.set("equip",getPara("equip"));
		house.set("aprice",getPara("aprice"));
		if (editflg){
			house.update();
		} else {
			house.set("userid",getPara("userid"));
			house.save();
		}
		
		try{
			if (Integer.valueOf(String.valueOf(house.get("status"))) == 1){
				User user = User.dao.findById(house.get("userid"));
				if (user != null && !StringUtil.isEmpty(user.getStr("wxid"))){
					WeiXinUtil.newHouseVerify(user.getStr("wxid"), house);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		renderText("操作成功！");
	}
	
	@Before(LoginInterceptor.class)
	public void view(){
		String picStr = getPara("value");
		if (StringUtil.isEmpty(picStr)){
			renderNull();
		} else {
			String [] picArray = picStr.split(",");
			setAttr("pic", picArray);
			render("pic.html");
		}
	}
	
	@Before(LoginInterceptor.class)
	public void configList(){
		int type = 1;
		try {
			type = getParaToInt("type");
		} catch (Exception e) {
		}
		int page = 1;
		if (!StringUtil.isEmpty(getPara("page"))){
			page = getParaToInt("page");
		}
		String andSql = "";
		String key = getPara("key");
		if (!StringUtil.isEmpty(key)){ 
			andSql = " and config.key like '%" + key +"%'";
		}
		String sqlSelect = "select config.* ";
		Page<Config> useres = Config.dao.paginate(page, 20, sqlSelect, " from w_config as config  where config.type =" +type + andSql +" order by config.subtype asc" );
		setAttr("page", useres);
		setAttr("key", key);
		render("configList"+type+".html");
	}
	
	@Before(LoginInterceptor.class)
	public void config(){
		Config config = Config.dao.findById(getPara("id"));
		if (config == null){
			//10 价格表 100 基础清扫服务 101 房内设施  
			int type = 0;
			try {
				type = getParaToInt("type");
			} catch (Exception e) {
			}
			config = new Config();
			config.set("type", type);
			setAttr("action", "添加");
		} else{
			setAttr("action", "修改");
		}
		setAttr("config", config);
		render("config"+config.getInt("type")+".html");
	}
	
	@Before(LoginInterceptor.class)
	public void configSave(){
		Config config = Config.dao.findById(getPara("id"));
		//10 价格表 100 基础清扫服务 101 房内设施  
		boolean editflg = true;
		if (config == null){
			editflg = false;
			config = new Config();
			config.set("type", getPara("type"));
		} 
		config.set("subtype", getPara("subtype"));
		config.set("key", getPara("key"));
		if (StringUtil.isEmpty(getPara("title"))){
			config.set("title", getPara("key"));
		} else {
			config.set("title", getPara("title"));
		}
		
		config.set("value", getPara("value"));
		try{
			if (editflg)
				config.update();
			else
				config.save();
		}catch (Exception e) {
			e.printStackTrace();
		}
		renderText("操作成功！");
	}
	
	@Before(LoginInterceptor.class)
	public void configDel(){
		Config.dao.deleteById(getPara("id"));
		renderText("操作成功！");
	}
	
	@Before(LoginInterceptor.class)
	public void user(){
		User user = User.dao.findById(getPara("id"));
		if (user == null){
			//0 普通用户 1 服务人员 2 房东   101 后台操作人员 1001 超级管理员
			int type = 0;
			try {
				type = getParaToInt("type");
			} catch (Exception e) {
			}
			user = new User();
			user.set("type", type);
			setAttr("action", "添加");
		} else{
			setAttr("action", "修改");
		}
		setAttr("user", user);
		render("user"+user.getInt("type")+".html");
	}
	
	
	@Before(LoginInterceptor.class)
	public void userSave(){
		User user = User.dao.findById(getPara("id"));
		boolean editflg = true;
		if (user == null){
			editflg = false;
			user = new User();
			user.set("type", getPara("type"));
			user.set("createtime", System.currentTimeMillis());
			user.set("password", getPara("password"));
			user.set("account", getPara("account"));
		} else {
			User existUser = User.dao.findFirst("select * from w_user where account = '"+getPara("account")+"' and id != "+getPara("id"));
			if (existUser != null){
				renderText("账号已存在！");
				return;
			}
		}
		user.set("name", getPara("name"));
		user.set("head", getPara("head"));
		user.set("age", getPara("age"));
		user.set("mobile", getPara("mobile"));
		user.set("scope", getPara("scope"));
		user.set("note", getPara("note"));
		if (!StringUtil.isEmpty(getPara("lon"))){
			user.set("lon",getPara("lon"));
		}
		if (!StringUtil.isEmpty(getPara("lat"))){
			user.set("lat",getPara("lat"));
		}
		user.set("rank",getPara("rank"));
		if (editflg){
			if(!StringUtil.isEmpty(getPara("money"))){
				user.set("money", getPara("money"));
			}
			user.update();
		} else
			user.save();
		renderText("操作成功！");
	}
	
	public void userDel(){
		User user = User.dao.findById(getPara("id"));
		if (user != null){
			user.set("valid", -1);
			user.update();
		}
		renderText("操作成功！");
	}
	
	
	public void calculate(){
		int num = getParaToInt("num");
		int result = 0;
		// 是否大于最大值
		Config maxConfig = Config.dao.findFirst("select * from w_config where type=10 and subtype =2 order by `key` desc limit 1");
		if (maxConfig != null){
			int maxkey = Integer.parseInt(String.valueOf(maxConfig.get("key")));
			if(num >= maxkey){
				Config lessMaxConfig =  Config.dao.findFirst("select * from w_config where type=10 and subtype =1 order by `value` desc limit 1");
				int value = maxConfig.getInt("value");
				result = lessMaxConfig.getInt("value") + (num- maxkey) * value ;
			} else {
				Config minConfig = Config.dao.findFirst("select * from w_config where type=10 and subtype =1 order by `key` asc limit 1");
				int minkey = Integer.parseInt(String.valueOf(minConfig.get("key")));
				if(num <= minkey){
					result = minConfig.getInt("value");
				} else {
					Config nearConfig = Config.dao.findFirst("select * from w_config where type=10 and subtype =1 and `key` >= "+num+" order by `key` asc limit 1");
					result = nearConfig.getInt("value");
				}
			}
		} else {
			//没有设置最大值，按小于等于最大值计算
			Config minConfig = Config.dao.findFirst("select * from w_config where type=10 and subtype =1 order by `key` asc limit 1");
			int minkey = Integer.parseInt(String.valueOf(minConfig.get("key")));
			if(num <= minkey){
				result = minConfig.getInt("value");
			} else {
				Config nearConfig = Config.dao.findFirst("select * from w_config where type=10 and subtype =1 and `key` >= 30 order by `key` asc limit 1");
				result = nearConfig.getInt("value");
			}
		}
		renderText("计算价格是："+result+"！");
		
	}

	
	@Before(LoginInterceptor.class)
	public void focusList(){
		int page = 1;
		if (!StringUtil.isEmpty(getPara("page"))){
			page = getParaToInt("page");
		}
		String sqlSelect = "select focus.* ";
		Page<Focus> focusList = Focus.dao.paginate(page, 20, sqlSelect, " from w_focus as focus " );
		setAttr("page", focusList);
		render("focusList.html");
	}
	
	@Before(LoginInterceptor.class)
	public void focus(){
		Focus focus = Focus.dao.findById(getPara("id"));
		if (focus == null){
			focus = new Focus();
			setAttr("action", "添加");
		} else{
			setAttr("action", "修改");
		}
		setAttr("focus", focus);
		render("focus.html");
	}
	
	@Before(LoginInterceptor.class)
	public void focusSave(){
		Focus focus = Focus.dao.findById(getPara("id"));
		boolean editflg = true;
		if (focus == null){
			editflg = false;
			focus = new Focus();
		} 
		focus.set("name", getPara("name"));
		focus.set("admin", getPara("admin"));
		focus.set("mobile", getPara("mobile"));
		focus.set("address", getPara("address"));
		focus.set("password", getPara("password"));
		if (editflg)
			focus.update();
		else
			focus.save();
		renderText("操作成功！");
	}
	
	/**
	 * 人工派单
	 */
	@Before(LoginInterceptor.class)
	public void dispatch(){
//		User sUser = User.dao.findById(getPara("userid"));
		List<Order> orderList = Order.dao.find("select * from w_order where status = 0 and id in (" +getPara("ids") +")");
		for(Order order:orderList){
			order.set("status", 1);
			order.set("sid",getPara("sid"));
			order.update();
			User user = User.dao.findById(getPara("sid"));
			try{
				user.set("ordercnt", user.getInt("ordercnt")+1);
				user.update();
			} catch (Exception e) {
			}
			
		}
		renderText("操作成功！");
	}
	
}

